﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;
using System.Drawing;
using System.Data.OleDb;

using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Util;
using NPOI.Util;
using System.Net;


namespace XJX.Page
{

    /// <summary>
    ///Helper 的摘要说明
    /// </summary>
    public class Helper
    {
        public Helper(){ }

        /// 上传图片
        /// </summary>
        /// <param name="file">通过form表达提交的文件</param>
        /// <param name="virpath">文件要保存的虚拟路径</param>
        public static void uploadImg(HttpPostedFile file, out string fn)
        {
            string savepath = HttpContext.Current.Server.MapPath("~/upload/pic/" + file.FileName);

            using (Image img = Bitmap.FromStream(file.InputStream))
            {
                img.Save(savepath);
            }

            fn=SaveToThumbnailImage(savepath);
        }

        //生成图片缩略图，传入全路径物理文件名称。
        private static string SaveToThumbnailImage(string FullFilePathName)
        {
            string tmp=DateTime.Now.Ticks.ToString() + System.IO.Path.GetExtension(FullFilePathName).ToLower();
            string sfile = HttpContext.Current.Server.MapPath("~/upload/pic/" + tmp) ;

            System.Drawing.Image image = null;
            System.Drawing.Image newimage = null;
            image = System.Drawing.Image.FromFile(FullFilePathName);//在这里装载了使用的文件。

            System.Drawing.Image.GetThumbnailImageAbort callb = null;
            newimage = image.GetThumbnailImage(100, 145, callb, new System.IntPtr());

            try
            {
                newimage.Save(sfile);
            }
            catch
            {
                tmp = "";
            }
            finally
            {
                newimage.Dispose();
                image.Dispose();//这两个对象需要释放资源，否则会出现文件正在被另一进程使用的错误。
                System.IO.File.Delete(FullFilePathName);
            }
            return tmp;
        }

        /// <summary>  
        /// 下载网站图片,如果图片不存在，则返回空值，返回空值，就表示图片不存在。  
        /// </summary>  
        /// <param name="picUrl"></param>  
        /// <returns></returns>  
        public static string DownFromWebImg(string picUrl)
        {
            string result = "";

            string imgtype = System.IO.Path.GetExtension(picUrl).ToLower();

            if (String.IsNullOrEmpty(picUrl) || String.IsNullOrEmpty(imgtype))
            {
                return result;
            }

            string filename = Guid.NewGuid() + imgtype;
            string file = HttpContext.Current.Server.MapPath("~/upload/pic/" + filename);

            try
            {
                WebClient webClient = new WebClient();   //命名空间为System.Net
                webClient.DownloadFile(picUrl, file);

                result = SaveToThumbnailImage(file);
                
            }
            catch { }
            return result;
        }  


        public static void uploadExcel(HttpPostedFile file,out int Value,out string Msg)
        {
            Value = 0;
            Msg = "";

            if (file == null)
            {
                throw new Exception("请先选择文件！");
            }
            else
            {

                string fileName = file.FileName;/*获取文件名： C:\Documents and Settings\Administrator\桌面\123.jpg*/
                string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();/*获取后缀名并转为小写： jpg*/

                int bytes = file.ContentLength;//获取文件的字节大小  

                if (!(suffix == "xls"))
                    throw new Exception("只能上传Excel文件");
                if (bytes > 1024 * 1024 * 10)
                    throw new Exception("文件最大只能传10M");

                if (bytes > 0)
                {
                    byte[] byts = new byte[file.ContentLength];

                    file.InputStream.Read(byts, 0, byts.Length);
                    file.InputStream.Close();

                    MemoryStream ms = new MemoryStream(byts);

                    //以下方法中的插入语句字段名称个数及顺序，要与Excel文件的标题对应起来（名称、个数、顺序）。
                    //存储过程中的语句insert familyinfo(sname,sex,rxnf,cid,fname,mobile,isteacher)
                    int i = ExcelRender.RenderToDb(ms, "Exec Add_New_Family  ", SqlHelper.ExecuteNonQuery);

                    if (i > 0)
                    {
                        Value = i;
                        Msg = "导入学生信息成功，共计导入：" + i.ToString().Trim() + "条！";
                    }
                    else
                    {
                        Value = 0;
                        Msg = "未导入此Excel表！";
                    }
                }
                else
                {
                    Value = -1;
                    Msg = "导入学生信息 失败！";
                }

            }

        }


        public static void uploadFileToFolder(HttpPostedFile file, out string fn)
        {
            fn = "";

            if (file == null)
            {
                throw new Exception("请先选择文件！");
            }
            else
            {
                string fileName = file.FileName;/*获取文件名： C:\Documents and Settings\Administrator\桌面\123.jpg*/
                string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();/*获取后缀名并转为小写： jpg*/
                int bytes = file.ContentLength;//获取文件的字节大小  
                //
                if (!(suffix == "mp3"))
                    throw new Exception("有声图书只支持mp3格式文件！");
                if (bytes > 1024 * 1024 * 50)
                    throw new Exception("文件最大只能传50M");

                string newfileName = DateTime.Now.ToString("yyyyMMddHHmmss");
                string fileDir = HttpContext.Current.Server.MapPath("~/upload/mp3/");
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }

                string saveDir = fileDir + newfileName + "." + suffix;

                file.SaveAs(saveDir);//保存mp3

                fn = newfileName + "." + suffix;
            }

        }

        //上传文件后，将信息保存至数据库出错，则回调删除文件方法。
        public static void DeleteUploadFile_BackCall(string fn)
        {
            if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/upload/mp3/" + fn)))
            {
                System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/upload/mp3/" + fn));
            }
        }


        //static string urlx = "http://sdk2.028lk.com:9880/sdk2/linkws.asmx";
        //static string CorpID = "CSJS001921";
        //static string Pwd = "zm0513@";
        //短信发送方法
        public static int SendShortMsg(string Mobile,string Content)
        {
            string urlx = ((ParamInfo)HttpContext.Current.Session["ParamInfo"]).UrlX;
            string CorpID = ((ParamInfo)HttpContext.Current.Session["ParamInfo"]).CorpID;
            string Pwd = ((ParamInfo)HttpContext.Current.Session["ParamInfo"]).PWD;

            //在添加了对上述webservice地址引用后，指定web服务名称为LWS（若是窗体程序，则会生成一个代理类文件Reference.cs）
            LWS.LinkWS WSS = new LWS.LinkWS();
            WSS.Url = urlx;

            int R;
            try
            {
                R = WSS.BatchSend(CorpID, Pwd, Mobile,Content, "", "");
            }
            catch (System.Net.WebException WebExcp)
            {
                return 100;//网络错误！
            }
            return R;       
        }

        //调用模板，形成发送内容
        public static int CallTemplater(int ID,string ToBorrowTitle,string TemplateName,string UID,string BID,string BorrowMobile,DateTime dt)
        {
           // return 1;
            //获得模板内容
            DataRow dr1=XJX.Page.Other.Get_Templater_Content_From_ID(ID);
            string tw = dr1[ToBorrowTitle].ToString();//标题
            string tc = dr1[TemplateName].ToString();//内容

            //获得图书信息
            DataRow dr2 = XJX.Page.Book.Get_One_Book_Info_From_BID_1(BID);

            //获得借阅人家庭信息
            FamilyInfo fi = XJX.Page.Family.Get_One_Family_Info_From_UID(UID);

            tw=tw.Replace("$bname$",dr2["bname"].ToString());

            tc = tc.Replace("$fname$", fi.Fname);
            tc = tc.Replace("$rxnf$", fi.RXNF);
            tc = tc.Replace("$cid$", fi.CID);
            tc = tc.Replace("$sname$", fi.Sname);
            tc = tc.Replace("$bname$", dr2["bname"].ToString());
            tc = tc.Replace("$jmobile$", BorrowMobile);//替换成借阅人的电话
            tc = tc.Replace("$bdate$",dt.ToString("YYYY/MM/dd HH:MM"));

            //下面调用站内信保存
            string ReturnFieldValue;   //返回字段值
            XJX.Page.SysMessage.Add_New_SysMsg(UID, BID, tw, tc,out ReturnFieldValue);

            int r = 0;
            ParamInfo pi = (ParamInfo)HttpContext.Current.Session["ParamInfo"];
            if (pi == null)
            {
                pi = XJX.Page.Other.Get_ALL_Param_For_Class();
                HttpContext.Current.Session["ParamInfo"] = pi;//保持参数信息
            }

            if (pi.SendStatus == "True")
            {
                r = SendShortMsg(fi.Mobile, tc);//调用短信发送
                if (r != 1)//保存未成功发送短信的通知
                {
                    XJX.Page.SysMessage.Add_New_NoSuccessShortMsg(ReturnFieldValue, ID.ToString(), System.Web.HttpContext.Current.Request.UserHostAddress);
                }
            }
            else
            {
                r = 1;//如果不需要发送短信，则直接将返回值设置为1
            }

            return r;
        }

        /// <summary>  
        /// DataTable导出到CSV  
        /// </summary>  
        /// <param name="table">DataTable类型的数据源</param>  
        /// <param name="file">需要导出的文件路径</param>  
        public static void dataTableToCsv(DataTable table, string file)
        {
            string title = "";
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
            for (int i = 0; i < table.Columns.Count; i++)
            {
                title += table.Columns[i].ColumnName + "\t"; //栏位：自动跳到下一单元格  
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);
            foreach (DataRow row in table.Rows)
            {
                string line = "";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    line += row[i].ToString().Trim() + "\t"; //内容：自动跳到下一单元格  
                }
                line = line.Substring(0, line.Length - 1) + "\n";
                sw.Write(line);
            }
            sw.Close();
            fs.Close();
        }

        /// <summary>  
        /// DataTable导出到Excel  
        /// </summary>  
        /// <param name="dt">DataTable类型的数据源</param>  
        /// <param name="FileType">文件类型</param>  
        /// <param name="FileName">文件名</param>  
        public static void CreateExcel(DataTable dt, string FileType, string FileName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
            HttpContext.Current.Response.ContentType = FileType;
            string colHeaders = string.Empty;
            string ls_item = string.Empty;
            DataRow[] myRow = dt.Select();
            int i = 0;
            int cl = dt.Columns.Count;
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                ls_item += dt.Columns[j].ColumnName + "\t"; //栏位：自动跳到下一单元格  
            }
            ls_item = ls_item.Substring(0, ls_item.Length - 1) + "\n";
            foreach (DataRow row in myRow)
            {
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        if (i != 9)
                            ls_item += row[i].ToString() + "\t";
                    }
                }
                HttpContext.Current.Response.Output.Write(ls_item);
                ls_item = string.Empty;
            }
            HttpContext.Current.Response.Output.Flush();
            HttpContext.Current.Response.End();
        }

        public static void CreateExcel(DataTable dt)
        {
            string FileName = Guid.NewGuid().ToString() + ".xls";

            string sNewFullFile = HttpContext.Current.Server.MapPath(FileName);
            try
            {
                File.Copy(HttpContext.Current.Server.MapPath("format.xls"), sNewFullFile);
            }
            catch (Exception er)
            {
                HttpContext.Current.Response.Write(er.Message);
                return;
            }
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=True;Data Source=" + sNewFullFile + ";Extended Properties=Excel 8.0;";
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn);
            OleDbCommand cmd = null;

            bool bRet = false;
            try
            {
                conn.Open();
                cmd = new OleDbCommand("create table [sheet4]([姓名] Text,[年龄] int,[电话] Text)", conn);
                cmd.ExecuteNonQuery();
                string strSQL = "INSERT INTO [Sheet4$] ([姓名], [年龄],[电话]) VALUES (?, ?, ?)";
                cmd = new OleDbCommand(strSQL, conn);
                for (int i = 0; i < 3; i++)
                {
                    cmd.Parameters.Add(i.ToString(), OleDbType.VarChar);
                }
                DataView dv = dt.DefaultView;
                foreach (DataRowView row in dv)
                {
                    cmd.Parameters[0].Value = row["name"].ToString();
                    cmd.Parameters[1].Value = (int)row["age"];
                    cmd.Parameters[2].Value = row["phone"].ToString();
                    cmd.ExecuteNonQuery();
                }
                bRet = true;
            }
            catch (Exception er)
            {
                HttpContext.Current.Response.Write(er.Message);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                conn.Dispose();
            }
            if (bRet)
                HttpContext.Current.Response.Redirect(FileName);
        }

        public static bool VerificationStr(string str)
        {
            bool b = false;

            if (str.IndexOf("'") != -1)
            {
                b = true;
            }
            if (str.IndexOf(";") != -1)
            {
                b = true;
            }

            if (str.IndexOf("|") != -1)
            {
                b = true;
            }
            if (str.IndexOf("\t") != -1)
            {
                b = true;
            }
            //if (str.IndexOf("\n") != -1)
            //{
            //    b = true;
            //}

            //在导出成Excel表时，如果出现了引号，将导致错误。
            if (str.IndexOf("\"") != -1)
            {
                b = true;
            }

            if (str.IndexOf("--") != -1)
            {
                b = true;
            }

            if (str.IndexOf("/") != -1)
            {
                b = true;
            }

            if (str.IndexOf("\\") != -1)
            {
                b = true;
            }

            if (str.IndexOf("*") != -1)
            {
                b = true;
            }

            if (str.IndexOf("(") != -1)
            {
                b = true;
            }

            if (str.IndexOf(")") != -1)
            {
                b = true;
            }

            if (str.IndexOf(" ") != -1)
            {
                b = true;
            }

            return b;
        }

        //MD5加密算法
        public static string MD5(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        }


        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //NPOI方式保存，将内存流保存到文件中。
        public static void SaveToFile(MemoryStream ms, string fileName)
        {
            //HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("WS" + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
            //HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            //HttpContext.Current.Response.Flush();
            //HttpContext.Current.Response.End();

            //HttpContext.Current.Response.Charset = "GB2312";
            //HttpContext.Current.Response.ContentType="application/vnd.ms-excel;charset=UTF-8";//告诉浏览器数据类型
            //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;fileName=" + HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)); ; //激活文件下载对话框
            //HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            //HttpContext.Current.Response.Flush();
            //HttpContext.Current.Response.End();

            HttpContext context = HttpContext.Current;
            context.Response.Clear();
            context.Response.Charset = "GB2312";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            // 文件名要先编码，中文文件名才不会有问题
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode(fileName));

            // 设置文件格式为 MS Excel
            context.Response.ContentType = "application/vnd.ms-excel";
            context.Response.BinaryWrite(ms.ToArray());

        }


        public static void SaveToFile(MemoryStream ms, string path,string fileName)
        {
            using (FileStream fs = new FileStream(path+fileName, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();

                fs.Write(data, 0, data.Length);
                fs.Flush();

                data = null;
            }
        }


        //NPOI方式保存，将内存流输出到浏览器中。
        public static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
        {
            if (context.Request.Browser.Browser == "IE")
                fileName = HttpUtility.UrlEncode(fileName);
            context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
            context.Response.BinaryWrite(ms.ToArray());
        }


        //使用DataTable数据生成内存流
        public static MemoryStream RenderToExcel(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            using (table)
            {
                IWorkbook workbook = new HSSFWorkbook();

                ISheet sheet = workbook.CreateSheet("第一个表");


                IRow headerRow = sheet.CreateRow(0);

                // handling header.
                foreach (DataColumn column in table.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value

                // handling value.
                int rowIndex = 1;

                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    foreach (DataColumn column in table.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }

                    rowIndex++;
                }

                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
            }
            return ms;
        }

        //使用DataReader数据生成内存流
        public static MemoryStream RenderToExcel(IDataReader reader)
        {
            MemoryStream ms = new MemoryStream();

            using (reader)
            {
                IWorkbook workbook = new HSSFWorkbook();

                ISheet sheet = workbook.CreateSheet();

                IRow headerRow = sheet.CreateRow(0);
                int cellCount = reader.FieldCount;

                // handling header.
                for (int i = 0; i < cellCount; i++)
                {
                    headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
                }

                // handling value.
                int rowIndex = 1;
                while (reader.Read())
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    for (int i = 0; i < cellCount; i++)
                    {
                        dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
                    }

                    rowIndex++;
                }

                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

            }
            return ms;
        }


        //生成较复杂的Excel表格形式。
        public static MemoryStream DataTableToExcel(DataTable table, string title)
        {
            MemoryStream ms = new MemoryStream();
            

            HSSFWorkbook hssfworkbook = new HSSFWorkbook();     //生成一个Excel文件，也称工作簿 

            ISheet sheet = hssfworkbook.CreateSheet("Sheet1");  //生成一个工作表，表名为sheet1
            hssfworkbook.CreateSheet("Sheet2");                 //生成一个工作表，表名为sheet2
            hssfworkbook.CreateSheet("Sheet3");                 //生成一个工作表，表名为sheet3

            sheet.FitToPage = false;//自适应页关闭。关闭后，缩放比例才起作用。打开后，全部行为一页内显示。
            sheet.PrintSetup.PaperSize = (short)PaperSize.A4; //(A4 210*297mm)
            sheet.PrintSetup.Landscape = true;//横向
            sheet.PrintSetup.Scale = 100;//缩放比例为100%
            //   sheet.PrintSetup.FitWidth = 1;//调整为一页宽


            sheet.SetMargin(MarginType.LeftMargin, (double).5); //实际宽度大约为0.5的三倍。
            sheet.SetMargin(MarginType.RightMargin, (double).5);
            sheet.SetMargin(MarginType.BottomMargin, (double).5);
            sheet.SetMargin(MarginType.TopMargin, (double).5);


            //使用CreateRow()创建行对象，CreateCell()创建单元格对象，再通过SetCellValue()设置单元格的内容。
            //面的是一个简单的例子，设置工作表的标题字体，并且合并第一行，前5列
            //Title  
            //string title = "一个简单的示例！";
            IRow titlerow = sheet.CreateRow(0);    //创建行对象  
            titlerow.HeightInPoints = 30F;
            ICell titlecell = titlerow.CreateCell(0);   //创建单元格对象  
            titlecell.SetCellValue(title);         //设置单元格内容  

            // 设置标题单元格样式  
            ICellStyle titlestyle = hssfworkbook.CreateCellStyle();
            titlestyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            IFont titlefont = hssfworkbook.CreateFont();
            titlefont.FontHeight = 20 * 20;
            titlestyle.SetFont(titlefont);
            titlecell.CellStyle = titlestyle;

            // 合并第0列到第4列的内容  
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, table.Columns.Count - 1));

            //在第二行，创建字段名称。
            IRow headerRow = sheet.CreateRow(1);
            headerRow.HeightInPoints = 16F;
            //创建字段名称的样式
            ICellStyle headerstyle = hssfworkbook.CreateCellStyle();
            headerstyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            headerstyle.BorderBottom = BorderStyle.Thin;
            headerstyle.BorderLeft = BorderStyle.Thin;
            headerstyle.BorderRight = BorderStyle.Thin;
            headerstyle.BorderTop = BorderStyle.Thin;
            IFont headerfont = hssfworkbook.CreateFont();
            headerfont.FontHeight = 16 * 16;
            headerstyle.SetFont(headerfont);

            //       NPOI没有行样式设置，据说是BUG

            // 字段名称信息处理
            foreach (DataColumn column in table.Columns)
            {
                ICell rc = headerRow.CreateCell(column.Ordinal);
                rc.CellStyle = headerstyle;
                rc.SetCellValue(column.Caption);//设置数据表的字段名称作为单元格的表头。
                sheet.SetColumnWidth(column.Ordinal, 70 * 70);//设置列宽
            }

            //单元格内容样式
            HSSFCellStyle contentstyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle(); //创建列头样式
            contentstyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
            contentstyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
            contentstyle.BorderBottom = BorderStyle.Thin;
            contentstyle.BorderLeft = BorderStyle.Thin;
            contentstyle.BorderRight = BorderStyle.Thin;
            contentstyle.BorderTop = BorderStyle.Thin;
            IFont contentfont = hssfworkbook.CreateFont();
            contentfont.FontHeight = 13 * 13;
            contentstyle.SetFont(contentfont);

            int rowIndex = 2;//内容输出从第3行开始。
            foreach (DataRow r in table.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);

                foreach (DataColumn column in table.Columns)
                {
                    HSSFCell cc = (HSSFCell)dataRow.CreateCell(column.Ordinal);
                    cc.CellStyle = contentstyle;
                    cc.SetCellValue(r[column].ToString());
                }
                rowIndex++;
            }

            hssfworkbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            return ms;
        }




    }



}